package com.xmmxjy.common.util;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xmm on 2017/1/17.
 */
public class XmlUtil {

    public static String xmlString = "<results version='1.0' ElapsedTime='111' Uuid='121231231'>" +
            "<status>success</status><message>成功</message>" + "</results>";

    public static Map<String,String> xmlToMap(String xml) {
        SAXReader sax=new SAXReader();//创建一个SAXReader对象
        System.out.println("xml : " + xml);
        InputStream in = new ByteArrayInputStream(xml.getBytes());
        Map<String,String> resultMap = new HashMap<String, String>();
        try {
            Document document=sax.read(in);
            Element results = document.getRootElement();
            System.out.println(results.getName());
            Attribute version = results.attribute("version");
            if (version != null) {
                resultMap.put("version", version.getValue());
            }
            Attribute elapsedTime = results.attribute("ElapsedTime");
            if (elapsedTime != null) {
                resultMap.put("ElapsedTime",elapsedTime.getValue());
            }
            Attribute uuid = results.attribute("Uuid");
            if (uuid != null) {
                resultMap.put("Uuid",uuid.getValue());
            }
            Element status = results.element("status");
            if (status != null) {
                resultMap.put("status",status.getTextTrim());
            }
            Element message = results.element("message");
            if (message != null) {
                resultMap.put("message",message.getTextTrim());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }

        return resultMap;
    }
    public static void main(String []args) {
        System.out.println(xmlToMap(xmlString));
    }
}
